package com.qiezi.util;


import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.qiezi.App;
import com.qiezi.bean.ResponseBean;
import com.qiezi.bean.SiteBean;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

public class Request {

//    static public String URL = "http://140.82.56.226/api";
    static public String URL = SiteBean.URL+"/api";
    public enum Api{

        getProductList("/Resource/getProductList"),
        getResourceList("/Resource/getResourceList"),
        getCategoryTwo("/Resource/getCategoryTwo"),
        getCategoryOne("/Resource/getCategoryOne"),
        download("/Login/download"),
        isAuth("/Resource/isAuth"),
        reportLookLen("/Resource/reportLookLen"),
        getAgentInfo("/Ucenter/getAgentInfo"),
        openAgent("/Ucenter/openAgent"),
        agentLogout("/Ucenter/agentLogout"),
        agentLogin("/Login/agentLogin"),
        getPaypal("/Ucenter/getPaypal"),
        modAddr("/Ucenter/modAddr"),
        paypal("/Ucenter/paypal"),
        buyMember("/Ucenter/buyMember"),
        getMemberType("/Ucenter/getMemberType"),
        getSiteClass("/Resource/getSiteClass"),
        getSiteList("/Resource/getSiteList"),
        checkVersion("/Ucenter/checkVersion")
        ;

        private String api;

        Api(String api){
            this.api = URL+api;
        }

        public String getApi() {
            return api;
        }
    }

    public static abstract class JsonCallback<T> extends Callback<JSONObject>
    {

        private Type type;

        protected JsonCallback(Type type){
            this.type = type;
        }

        private String errorString(Exception e){
            String msg = e.toString();
            Log.d("", "onError: "+msg);
            if (msg.contains("Canceled") || msg.contains("Socket closed"))return null;
            msg = msg.substring(msg.indexOf(":")+1);

            return msg;
        }

        public abstract void onSueccess(ResponseBean<T> data);
        public abstract void onFailure(String msg);




        @Override
        public void onResponse(JSONObject response, int id) {

            ResponseBean<T> data = JSON.parseObject(response.toJSONString(),new TypeReference<ResponseBean<T>>(type){});
            if (data == null){
                onFailure("数据加载失败");
                return;
            }
//            System.out.println("onResponse: "+data);
            if (data.isSuccess()){
                onSueccess(data);
            }else if (data.getMsg().contains("token")){
                onFailure("登录证书过期，正在重新申请");
                App.getInstance().download(true);
            }else {
                onFailure(data.getMsg());
            }
        }

        @Override
        public void onError(Call call, Response response, Exception e, int id){
            onFailure(errorString(e));
        }

        @Override
        public JSONObject parseNetworkResponse(Response response, int id) throws IOException
        {
            return JSON.parseObject(response.body().string());
        }
    }
    /**
     * 获取精确到秒的时间戳
     * @return
     */
    public static String getSecondTimestamp(Date date){
        if (null == date) {
            return "0";
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return timestamp.substring(0,length-3);
        } else {
            return "0";
        }
    }



    public static final String SIGNATURE = "!wishing!";

    public static RequestCall post(Api api, Map<String,String> params, JsonCallback callback){

        if (params == null) params = new HashMap<>();

        if (App.getInstance().isLogin() || api == Api.agentLogin){
            String timestamp = getSecondTimestamp(new Date());
            String sign = AESUtil.md5(timestamp+SIGNATURE);

            params.put("token", App.getInstance().getToken());
            params.put("time",timestamp);
            params.put("sign",sign);
        }else if (api != Api.download){
            App.getInstance().download(true);
            callback.onError(null,null,new Exception("登录证书过期，正在重新申请"),-1);
            return null;
        }
        RequestCall cell = OkHttpUtils.post().url(api.getApi()).params(params).build();
        if (callback != null) cell.execute(callback);
        return cell;
    }

}
